package cn.libinal.scloud.base.common.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Sets;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.ObjectUtils;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.util.Set;

/**
 * @author libinal
 */
@Data
@MappedSuperclass
public class JpaBaseEntity implements Serializable {

    private static final long serialVersionUID = -8683854536272193347L;

    @Id
    @GeneratedValue(generator = "snowFlakeId")
    @GenericGenerator(name = "snowFlakeId", strategy = "cn.libinal.scloud.base.common.entity.SnowflakeId")
    @Column(name = "id", length = 36)
    private String id;

    @JsonIgnore
    public static String[] getNullProperties(Object o) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(o);
        PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
        Set<String> nullProperties = Sets.newHashSet();

        for (PropertyDescriptor descriptor: propertyDescriptors) {
           Object value = beanWrapper.getPropertyValue(descriptor.getName());
            if (ObjectUtils.isEmpty(value)) {
                nullProperties.add(descriptor.getName());
            }
        }
        return nullProperties.toArray(new String[]{});
    }
}
